package de.tum.wi.som.prio.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.tum.wi.som.Node;
import de.tum.wi.som.Project;
import de.tum.wi.som.prio.PriorityRule;
import de.tum.wi.som.util.PrioUtil;

public class MostTotalSuccessors implements PriorityRule{
	 
	@Override
	    public void prioritize(Project project) {

	        List<Node> scheduledNodes = new ArrayList<Node>();
	        List<Node> remainingNodes = new ArrayList<Node>();
	        remainingNodes.addAll(Arrays.asList(project.getNodes()));
	        List<Node> accessibleNodes;
	        Node dummyNode = new Node(0, new int[0]);

	        while (!remainingNodes.isEmpty()) {
	            accessibleNodes = PrioUtil.determineAccesibleNodes(scheduledNodes, project.getSource(), remainingNodes);
	            if (accessibleNodes.size() == 0) {
	            	System.err.println("No accessible nodes found in MaximumCriticalSuccessor");
	            	return;
	            }
	            Node candidateNode = dummyNode;
	            int maxTotalSuccessors = 0;

	            for (Node node : accessibleNodes) {
	                int totalSuccessors = getTotalSuccessors(node);
	                if (candidateNode == dummyNode || totalSuccessors > maxTotalSuccessors) {
	                    candidateNode = node;
	                    maxTotalSuccessors = totalSuccessors;
	                }
	            }
	            scheduledNodes.add(candidateNode);
	            remainingNodes.remove(candidateNode);
	        }
	        project.setNodes(scheduledNodes.toArray(new Node[scheduledNodes.size()]));

	    }

	    private int getTotalSuccessors(Node node) {
	        int totalSuccessors = 0;
	    	for (Node successor : node.getSuccessors()) {
	        	totalSuccessors++;
	        	totalSuccessors += getTotalSuccessors(successor);
	        }
	    	return totalSuccessors;
	    }
	    
	    @Override
		public String toString(){
			return "MostTotalSuccessors";
		}
}
